package com.ip.student.service;

import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.ip.student.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ip.student.mapper.BaseClassMapper;
import com.ip.student.models.service.IBaseClassService;
import com.ip.student.models.bo.BaseClassSaveBO;
import com.ip.student.models.dto.BaseClassDTO;

/**
 * 班级信息控制器
 *
 * @author 张景奇
 * @Date 2025-10-25 10:55:52
 */
@DubboService
public class BaseClassServiceImpl extends ServiceImpl<BaseClassMapper, BaseClassDTO> implements IBaseClassService{

    private static final Logger log = LoggerFactory.getLogger(BaseClassServiceImpl.class);

    @Resource
    private YmlConfig ymlConfig;

    @Override
    public boolean add(BaseClassSaveBO saveBO) {
        log.info("服务层接收到的班级信息: {}", saveBO);
        BaseClassDTO dto = new BaseClassDTO();
        BeanUtils.copyProperties(saveBO,dto);
        log.info("复制属性后的DTO: {}", dto);
        
        // 如果前端传回的ID为null，则使用雪花算法生成ID
        if (saveBO.getClassId() == null) {
            Long id = ymlConfig.getPkId();
            // 确保生成的ID为正数且在Integer范围内
            if (id < 0) {
                id = Math.abs(id);
            }
            // 确保ID在Integer范围内
            if (id > Integer.MAX_VALUE) {
                id = id % Integer.MAX_VALUE;
            }
            // 确保ID不为0
            if (id == 0) {
                id = 1L;
            }
            dto.setId(id);
            // 同时设置classId字段
            dto.setClassId(id.intValue());
        } else {
            dto.setId(saveBO.getClassId().longValue());
            dto.setClassId(saveBO.getClassId());
        }
        
        if (saveBO.getSchoolId() != null) {
            dto.setSchoolId(saveBO.getSchoolId());
        }
        // 设置其他可能为空字符串的字段
        if (saveBO.getHeadTeacherId() != null && !saveBO.getHeadTeacherId().equals("")) {
            dto.setHeadTeacherId(saveBO.getHeadTeacherId());
        }
        // 如果班级编号为空，则使用雪花算法生成编码
        if (saveBO.getClassCode() == null || saveBO.getClassCode().trim().isEmpty()) {
            Long id = ymlConfig.getPkId();
            // 确保生成的ID为正数
            if (id < 0) {
                id = Math.abs(id);
            }
            // 确保ID在Integer范围内
            if (id > Integer.MAX_VALUE) {
                id = id % Integer.MAX_VALUE;
            }
            // 确保ID不为0
            if (id == 0) {
                id = 1L;
            }
            dto.setClassCode("CLASS-" + id);
        } else {
            dto.setClassCode(saveBO.getClassCode());
        }
        log.info("处理后的DTO: {}", dto);
        return this.insert(dto);
    }
}